import CopyrightFooter from '@/components/CopyrightFooter';
import TopBar from '@/components/TopBar';
import { handleEvent } from '@/services/center';
import {
  editPage,
  getCurrentPositionStep,
  getPositionStep,
  handleAddInfo,
  handleParams,
} from '@/services/login';
import { formatImgItem, formatNumber, getImgUrl, jumpUrl } from '@/utils';
import { useRequest } from 'ahooks';
import { Button, Col, Divider, Flex, Form, InputNumber, Row, Steps, message } from 'antd';
import dayjs from 'dayjs';
import localeData from 'dayjs/plugin/localeData';
import weekday from 'dayjs/plugin/weekday';
import React, { useEffect, useMemo, useState } from 'react';
import { getLocale, useIntl, useModel } from 'umi';
import MatchAnimationModal from './components/MatchAnimationModal';
import StepFour from './components/StepFour';
import StepLive from './components/StepLive';
import StepOne from './components/StepOne';
import StepThree from './components/StepThree';
import StepTwo from './components/StepTwo';
import { stepList } from './data';
import './index.less';

// 不设置日期默认值会报错
dayjs.extend(weekday);
dayjs.extend(localeData);
const Index: React.FC = () => {
  const intl = useIntl();
  const isEn = getLocale() == 'en-US';
  // 获取上传图片的数据
  const { uploadParams, setUploadParams } = useModel('uploadModel');
  // 维护居住和工作的全局step
  const { setStep, step, runConfig, key } = useModel('stepModel');
  const [index, setIndex] = useState(0);
  // 是否填写过
  const [writed, setWrited] = useState(false);
  // 贷款额度
  const [amount, setAmount] = useState(0);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  // 匹配动画弹窗
  const [visible, setVisible] = useState(false);
  // 用户信息
  const { user: userInfo, run: runUser } = useModel('userModel');

  // 获取贷款额度列表
  const { data, run } = useRequest(() => handleParams({ code: 'Auth_Amount' }));
  const configList = data?.data?.Auth_Amount[0].value.split(',');

  const { data: stepVal } = useRequest(getPositionStep);
  const { data: currentStepVal } = useRequest(getCurrentPositionStep);

  // 过滤步骤
  const list = useMemo(() => {
    const ids = stepVal?.data?.map((item: Record<string, any>) => item.id) || [];

    return stepList.filter((item) => {
      if (ids?.includes(item?.key.toString())) {
        return item;
      }
    });
  }, [stepVal]);

  // eslint-disable-next-line react-hooks/exhaustive-deps

  const handleStep = (num: number) => {
    setIndex(index + num);
  };

  // 初始化
  useEffect(() => {
    runConfig();
  }, [runConfig]);
  useEffect(() => {
    const value = userInfo || {};
    if (Object.keys(value)?.length > 0 && currentStepVal?.data.length > 0) {
      const {
        addressProof,
        bankMonthlyStatement,
        workProof,
        vehicleProof,
        estateProof,
        stockProof,
        cryptocurrencyProof,
        insuranceProof,
        otherProof,
        creditProof,
        birthday,
        graduationTime,
        userWorkInfo,
        loanInfo,
        idCardImg,
        idCardImg1,
        statementsConfirmFlag,
        cardNumber,
        applyAmount,
        ...rest
      } = value;
      const { ...val } = userWorkInfo || {};
      setAmount(applyAmount || 0);
      // 填过就不需要调接口

      if (!applyAmount && value.hasOwnProperty('applyAmount')) {
        run();
      } else {
        const list = currentStepVal?.data.filter((item: any) => {
          return item.status == 1;
        });

        setIndex(
          Number(
            list.length > 0 ? list[0].id : currentStepVal?.data[currentStepVal?.data.length - 1].id,
          ) - 1,
        );
      }
      setWrited(applyAmount);
      // 设置表单
      form.setFieldsValue({
        ...(birthday ? { birthday: dayjs(birthday) } : {}),
        // 入学时间
        ...(graduationTime ? { graduationTime: dayjs(graduationTime) } : {}),
        ...(cardNumber ? { cardNumber1: cardNumber.slice(0, 7) } : {}),
        ...(cardNumber ? { cardNumber2: cardNumber.slice(8, 9) } : {}),
        ...(loanInfo ? { loanInfo: JSON.parse(loanInfo) } : {}),
        ...rest,
        ...val,
      });
      // 设置全局上传的数据
      setUploadParams({
        idCard: {
          front: idCardImg,
          back: idCardImg1,
        },
        statementsConfirmFlag,
        bankMonthlyStatement: formatImgItem(bankMonthlyStatement),
        workProof: formatImgItem(workProof),
        vehicleProof: formatImgItem(vehicleProof),
        estateProof: formatImgItem(estateProof),
        stockProof: formatImgItem(stockProof),
        cryptocurrencyProof: formatImgItem(cryptocurrencyProof),
        otherProof: formatImgItem(otherProof),
        creditProof: formatImgItem(creditProof),
        addressProof: formatImgItem(addressProof),
        insuranceProof: JSON.parse(insuranceProof || '[]').map((item: any) => {
          const { urls, ...rest } = item;
          return {
            ...rest,
            urls: formatImgItem(urls),
          };
        }),
      });
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [userInfo, form, currentStepVal]);
  const keyList = Object.values(key || {})
    .flat()
    .map((item) => item.key);
  // 显示步数
  const renderCompnents = useMemo(() => {
    const key = list[index]?.key || 1;
    switch (key) {
      case 1:
        return {
          components: <StepOne needPassWord={keyList.includes('password')} form={form} />,
          nextTag: 'Personal_Information_next',
          inTag: 'Personal_Information_access',
        };
      case 2:
        return {
          components: <StepLive form={form} />,
          nextTag: 'Personal_Live_next',
          inTag: 'Personal_Live_access',
        };
      case 3:
        return {
          components: <StepTwo form={form} />,
          nextTag: 'Work_Information_next',
          inTag: 'Work_Information_access',
        };

      case 4:
        return {
          components: <StepThree form={form} />,
          nextTag: 'Financial_situation_next',
          inTag: 'Financial_situation_access',
        };
      case 5:
        return {
          components: <StepFour />,
          nextTag: 'Upload_submit',
          inTag: 'Upload_access',
        };
      default:
        return {};
    }
  }, [index, form, list, keyList]);
  const { components, inTag, nextTag } = renderCompnents;
  useEffect(() => {
    if (inTag) {
      handleEvent(inTag);
    }
  }, [inTag]);

  return (
    <>
      <div>
        <div className="warrper">
          <div style={{ padding: '7px 130px 0' }}>
            <TopBar
              localOverlayClassName="info_local_class"
              needWords={false}
              dark
              isCommon={false}
            />
          </div>
          <Divider className="warrper_divier" />
          <div className="common">
            <div className="info">
              {writed ? (
                <div className="info_main">
                  <div className="info_left">
                    <Flex align="center" gap={9} style={{ marginBottom: 15 }}>
                      <div style={{ fontSize: 20, color: '#333', fontWeight: 500 }}>
                        {intl.formatMessage({ id: 'center.step' })}
                      </div>
                      <div
                        style={{ width: 5, height: 5, borderRadius: '50%', background: '#666' }}
                      />
                      <Flex
                        align="center"
                        justify="center"
                        style={{
                          border: '1px solid #666666',
                          color: '#666666',
                          fontSize: 10,
                          minWidth: 18,
                          height: 18,
                          borderRadius: '50%',
                        }}
                      >
                        {index + 1}
                      </Flex>
                      <div style={{ fontSize: 20, color: '#666' }}>{list[index]?.title}</div>
                    </Flex>
                    <Steps
                      labelPlacement="vertical"
                      className="info_step"
                      current={index}
                      direction="horizontal"
                      items={
                        list.map((item) => {
                          return {
                            key: item.key,
                          };
                        }) as any
                      }
                    />
                  </div>
                  <div className="info_right">
                    <div className="info_right_form" style={{ padding: '0 54px' }}>
                      <Form
                        requiredMark={false}
                        layout="vertical"
                        onFinish={async (values) => {
                          // 居住信息和工作信息

                          if (2 == list[index].key && step == 1) {
                            setStep(2);
                            return;
                          }
                          if (
                            3 == list[index].key &&
                            step == 1 &&
                            form.getFieldValue('occupation') != 7
                          ) {
                            setStep(2);
                            return;
                          }

                          const {
                            mobile,
                            loanInfo,
                            birthday,
                            graduationTime,
                            cardNumber2,
                            cardNumber1,
                            ...rest
                          } = values;
                          let uploadData: any = {};
                          if (list[index].key == 5) {
                            const {
                              idCard: { back, front },
                              addressProof,
                              bankMonthlyStatement,
                              estateProof,
                              stockProof,
                              vehicleProof,
                              insuranceProof,
                              cryptocurrencyProof,
                              otherProof,
                              creditProof,
                              workProof,
                              statementsConfirmFlag,
                            } = uploadParams;
                            uploadData = {
                              idCardImg: front,
                              idCardImg1: back,
                              addressProof: getImgUrl(addressProof),
                              ...(bankMonthlyStatement.length > 0
                                ? { bankMonthlyStatement: getImgUrl(bankMonthlyStatement) }
                                : {}),
                              estateProof: getImgUrl(estateProof),
                              stockProof: getImgUrl(stockProof),
                              vehicleProof: getImgUrl(vehicleProof),
                              ...(insuranceProof?.length > 0
                                ? {
                                    insuranceProof: JSON.stringify(
                                      insuranceProof.map((item: any) => {
                                        const { urls, ...rest } = item as any;
                                        return {
                                          ...rest,
                                          urls: getImgUrl(urls),
                                        };
                                      }),
                                    ),
                                  }
                                : ''),
                              cryptocurrencyProof: getImgUrl(cryptocurrencyProof),
                              otherProof: getImgUrl(otherProof),
                              creditProof: getImgUrl(creditProof),
                              workProof: getImgUrl(workProof),
                              statementsConfirmFlag,
                            };
                          }

                          setLoading(true);
                          try {
                            const { code, message: msg } = await handleAddInfo({
                              type: list[index].key,
                              ...(list[index].key == 5
                                ? uploadData
                                : {
                                    ...rest,
                                    ...(loanInfo ? { loanInfo: JSON.stringify(loanInfo) } : {}),
                                    ...(cardNumber1
                                      ? { cardNumber: `${cardNumber1}(${cardNumber2})` }
                                      : {}),
                                    ...(birthday
                                      ? { birthday: dayjs(birthday).format('YYYY-MM-DD') }
                                      : {}),
                                    ...(graduationTime
                                      ? {
                                          graduationTime:
                                            dayjs(graduationTime).format('YYYY-MM-DD'),
                                        }
                                      : {}),
                                    ...(list[index].key == 2
                                      ? { livingSituation: form.getFieldValue('livingSituation') }
                                      : {}),
                                    ...(list[index].key == 3
                                      ? { occupation: form.getFieldValue('occupation') }
                                      : {}),
                                  }),
                            });
                            if (code === '100200') {
                              if (list.length - 1 == index) {
                                message.success(msg);

                                setVisible(true);
                              } else {
                                handleStep(1);
                                setStep(1);
                              }
                              setLoading(false);
                            }
                          } catch {
                            setLoading(false);
                          }
                          handleEvent(nextTag || '');
                        }}
                        form={form}
                        name="dependencies"
                        autoComplete="off"
                      >
                        {components}

                        {/* 下一步和上一步按钮 */}
                        <div className="info_right_form_btn">
                          <Form.Item className="form_btn">
                            <Button
                              block
                              loading={loading}
                              style={{
                                padding: '29px 76px',
                                fontSize: 16,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                borderRadius: 28,
                              }}
                              type="primary"
                              htmlType="submit"
                            >
                              {intl.formatMessage({
                                id: index == list.length - 1 ? 'home.submit' : 'home.next',
                              })}
                            </Button>
                          </Form.Item>
                          {index !== 0 && (
                            <Button
                              block
                              onClick={() => {
                                // 居住信息和工作信息

                                if ([2, 3].includes(list[index].key)) {
                                  if (step == 2) {
                                    setStep(1);
                                  } else {
                                    if (list[index - 1].key == 2) {
                                      setStep(2);
                                    }
                                    handleStep(-1);
                                  }
                                } else {
                                  if ([2, 3].includes(list[index - 1].key)) {
                                    // 无业的时候没有第二步
                                    if (
                                      form.getFieldValue('occupation') == 7 &&
                                      list[index - 1].key == 3
                                    ) {
                                      setStep(1);
                                    } else {
                                      setStep(2);
                                    }
                                  }
                                  handleStep(-1);
                                }
                              }}
                              className="info_right_form_btn_pre"
                              style={{
                                padding: '29px 76px',
                                fontSize: 16,
                                display: 'flex',
                                alignItems: 'center',
                                color: '#333333',
                                background: '#D7D7D7',
                                justifyContent: 'center',
                                borderRadius: 28,
                                border: 'none',
                              }}
                            >
                              {intl.formatMessage({ id: 'home.pre' })}
                            </Button>
                          )}
                        </div>
                      </Form>
                    </div>
                  </div>
                </div>
              ) : (
                <div className="info_content">
                  <div style={{ fontSize: isEn ? 30 : 50, color: '#000' }}>
                    {intl.formatMessage(
                      { id: 'center.hope' },
                      {
                        amount: (
                          <span style={{ color: '#0270DF' }}>
                            {intl.formatMessage({ id: 'center.hope_amount' })}
                          </span>
                        ),
                      },
                    )}
                  </div>
                  <div
                    style={{
                      margin: '30px 0 50px 0',
                      color: '#868686',
                      fontSize: 24,
                      lineHeight: '30px',
                    }}
                  >
                    {intl.formatMessage({ id: 'center.hope_tips' })}
                    <span style={{ fontWeight: 500 }}>
                      {intl.formatMessage({ id: 'center.hope_tips_word' })}
                    </span>
                  </div>
                  <InputNumber
                    addonBefore="$"
                    className="inputNumber"
                    controls={false}
                    // suffix={intl.formatMessage({ id: 'home.total_money' }, { num: '' })}
                    value={amount}
                    formatter={(value) => formatNumber(value || 0, false)}
                    onChange={(e) => {
                      setAmount(e || 0);
                    }}
                    max={10000000}
                  />
                  <Divider />
                  <Row gutter={[14, 32]}>
                    {configList?.map((v: number) => {
                      return (
                        <Col
                          span={12}
                          key={v}
                          onClick={() => {
                            setAmount(v);
                          }}
                        >
                          <div className={`${v == amount ? 'money_active' : ''} money_item`}>
                            {formatNumber(v)}
                          </div>
                        </Col>
                      );
                    })}
                  </Row>
                  <Button
                    style={{ height: 60, margin: '60px 0 100px 0', borderRadius: 28, fontSize: 24 }}
                    block
                    type="primary"
                    disabled={!amount}
                    onClick={async () => {
                      await editPage({
                        applyAmount: amount,
                      });
                      setWrited(true);
                    }}
                  >
                    {intl.formatMessage({ id: 'center.hope_start' })}
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
        <MatchAnimationModal
          visible={visible}
          handleCancel={() => {
            setVisible(false);
          }}
          handleOk={() => {
            // 更新用户信息
            runUser();
            setVisible(false);
            jumpUrl('/product');
          }}
        />
        {/* 底部 */}
        <div className="info_footer">
          <CopyrightFooter />
        </div>
      </div>
    </>
  );
};

export default Index;
